<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>录音</title>
    </head>
    <body>
        <div>
            使用阿里云识别前，请自行添加申请的id和key。
        </div>
        <input type="button" value="录音开启" onclick="startRecord()" />
        <input type="button" value="录音停止" onclick="endRecord()" />
        <input type="button" value="播放录音" onclick="playRecord()" />
        <input type="button" value="阿里云识别" onclick="transRecord()" />
        <audio autoplay controls id="audio"></audio>
    </body>
<script src="recorder.js"></script>
<script>
var oDiv = document.getElementById('box'),
    audio = document.getElementById('audio'),
    recorder = null;

function startRecord() {
    if (!recorder) {
        recorder = new Recorder({
            sampleRate: 16000       // 阿里云要求16000的采样率
        });
    }
    recorder.start();
}
function endRecord (e) {
    recorder && recorder.stop();
}
function transRecord (e) {
    let pcm = recorder.getPCMBlob(),
        formdata = new FormData();

    formdata.append('file', pcm);

    fetch('/speech', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        body: formdata
    }).then(function(response) {
        return response.json();
    }, function() {
        alert('请添加下阿里云的id和key');
    }).then(function(data) {
        console.log(data);
    });
}
function playRecord() {
    recorder && recorder.play(audio);
}
</script>
</html>
